#include <form.h>
#include <stdio.h>
#include "macro.h"
#include "TextForm.h"
#include "ioctl_op.h"
#include "utils.h"

extern FIELD *field[FIELD_CNT+1]; //The last one must be NULL
extern FORM *my_form;
void Handle_WRITE(char *ifname) {
	char *p1,*p2;
	char msgbuf[1024];
	char fbuf[2][10];
	int setaddr;
	int setval;
	int field_idx;
	int ret;
	field_idx = field_index(current_field(my_form));
	memset(fbuf,0,sizeof(fbuf));
	switch (field_idx) {
		case CR_NAME:
		case CR_VALUE:
			p1 = field_buffer(field[CR_NAME],0);
			p2 = field_buffer(field[CR_VALUE],0);
			strncpy(fbuf[0],p1,9);
			strncpy(fbuf[1],p2,9);
			rtrim(fbuf[0]);
			rtrim(fbuf[1]);
			sscanf(fbuf[0],"%x",&setaddr);
			sscanf(fbuf[1],"%x",&setval);
			if(setaddr > 0x1000) {
				SetMessage("Invalid CR");
				SetResult("Error");
				return;
			}
			sprintf(msgbuf,"Set PHY CR:%03x,  Value:%08x",setaddr,setval);
			SetMessage(msgbuf);
			ret = gDevVal(ifname,"WRPhy",setaddr,setval);
			sprintf(msgbuf,"%s","Success");
			if(ret < 0) 
				sprintf(msgbuf,"%s","Get Device Value Fail");
			SetResult(msgbuf);	
			
			break;
		case ADDR_NAME :
		case ADDR_VALUE:
            p1 = field_buffer(field[ADDR_NAME],0);
            p2 = field_buffer(field[ADDR_VALUE],0);
            strncpy(fbuf[0],p1,9);
            strncpy(fbuf[1],p2,9);
            rtrim(fbuf[0]);
            rtrim(fbuf[1]);
            sscanf(fbuf[0],"%x",&setaddr);
            sscanf(fbuf[1],"%x",&setval);
            if(setaddr > 0x1000) {
                SetMessage("Invalid Address");
                SetResult("Error");
				return ;
            }

            sprintf(msgbuf,"Set MAC ADDR:%03x,  Value:%08x",setaddr,setval);
            SetMessage(msgbuf);
            ret = gDevVal(ifname,"WRMAC",setaddr,setval);
			sprintf(msgbuf,"%s","Success");
            if(ret < 0)
                sprintf(msgbuf,"%s","Get Device Value Fail");
            SetResult(msgbuf);


			break;
		default:
			SetMessage("Serious Error!! Unexpect Field Index");
	}	
}
